package com.smq.chatserver.aspect;

import com.alibaba.fastjson.JSONObject;
import com.smq.chatserver.util.ReqIpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Pointcut("execution(public * com.smq.chatserver.controller.*.*(..))")
    public void requestAspect() {
    }

    @Before(value = "requestAspect()")
    public void methodBefore(JoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //打印请求内容
        log.info("\t请求开始 =>> 来源{}, 资源：{},方式：{}，参数：{}",
                ReqIpUtils.getIpAddress(request),
                request.getRequestURL().toString(),
                request.getMethod(),
                Arrays.toString(joinPoint.getArgs()));
    }

    //在方法执行完结后打印返回内容
    @AfterReturning(returning = "o", pointcut = "requestAspect()")
    public void methodAfterReturing(Object o) {
        log.info("\t请求结束 ==> 返回数据:{}", JSONObject.toJSONString(o));
    }
}